package com.AuthServer.utils;

import com.AuthServer.service.SecretService;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
public class JwtUtil {

    public static String createJwt(String key, RedisTemplate<String,Object> template,SecretService service){
        String secret = getSecret(template,service);
        Map<String,Object> header = new HashMap<>();
        header.put("alg","HS256");
        header.put("typ","JWT");
        JWTCreator.Builder builder = JWT.create();
        return builder.withHeader(header).withClaim("key",key).sign(Algorithm.HMAC256(secret));
    }

    public static String parseJwt(String token,RedisTemplate<String,Object> template,SecretService service) throws SignatureVerificationException, AlgorithmMismatchException, TokenExpiredException {
        String secret = getSecret(template,service);
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
        DecodedJWT decodedJWT = verifier.verify(token);
        return decodedJWT.getClaim("key").asString();
    }

    private static String getSecret(RedisTemplate<String,Object> template,SecretService service){
        String secret = (String) template.opsForValue().get("key_secret");
        if (secret == null){
            secret = service.getById(1).getSecret();
            template.opsForValue().set("key_secret",secret,15, TimeUnit.DAYS);
        }
        return secret;
    }
}
